package com.biz.primus.ms.commodity.dao.specification;

import com.biz.primus.commodity.vo.saleTag.SaleTagProductSearchReqVo;
import com.biz.primus.ms.commodity.dao.po.Product;
import com.biz.primus.ms.commodity.dao.po.SaleTag;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Objects;

/**
 * Created by aaa on 2017/6/30.
 */
public class SaleTagProductSpecification implements Specification<Product> {

    private SaleTagProductSearchReqVo reqVo;

    public SaleTagProductSpecification(SaleTagProductSearchReqVo reqVo) {
        this.reqVo = reqVo;
    }

    @Override
    public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        // 按照创建时间倒序
        query.orderBy(cb.desc(root.get("createTimestamp")));
        // 查询未删除的
        predicates.add(cb.equal(root.get("deleteFlag").as(Boolean.class), Boolean.FALSE));

        if(StringUtils.isNotEmpty(reqVo.getSearchValue())){
            // 按照传入参数查找字段
            Predicate predicate;
            if (Objects.equals(reqVo.getSearchKey(),"name")){
                predicate = cb.like(root.get(reqVo.getSearchKey()).as(String.class), "%"+reqVo.getSearchValue()+"%");
            }else {
                predicate = cb.equal(root.get(reqVo.getSearchKey()), reqVo.getSearchValue());
            }
            predicates.add(predicate);
        }
        ListJoin<Product, SaleTag> join = root.join(root.getModel().getList("saleTags", SaleTag.class), JoinType.LEFT);
        predicates.add(cb.equal(join.get("id").as(Long.class), reqVo.getSaleTagId()));
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        return query.getRestriction();
    }

}
